﻿using UnityEngine;
using System.Collections;

public class Destructible : MonoBehaviour {

    public float radius = 0.5f;
    public float maxLife = 10;
    public float regen = 0.2f;

    public float life;
    public int images;
    public exSpriteAnimation healthIcon;

    public void Attack(float damage)
    {
        if (life > 0)
        {
            life -= damage;
            UpdateHeart();
        }
    }

	// Use this for initialization
	void Start () {
        if (healthIcon)
            healthIcon.renderer.enabled = false;
        life = maxLife;
	}
	
	// Update is called once per frame
	void Update ()
    {
        if (life > 0 && life < maxLife)
        {
            life += Time.deltaTime * regen;
            if (life > maxLife)
                StartCoroutine(HideHeart());
            else
                UpdateHeart();
        }
	}

    void UpdateHeart()
    {
        if (healthIcon)
        {
            healthIcon.renderer.enabled = true;
            if (life >= 0)
            {
                var frames = healthIcon.defaultAnimation.frameInfos;
                healthIcon.SetFrame(healthIcon.defaultAnimation.name, (int)(frames.Count * life / maxLife));
            }
            else
            {
                healthIcon.Play("dead");
                this.PlayAnim("die", true);
                StartCoroutine(HideHeart());
            }
        }
    }

    IEnumerator HideHeart()
    {
        yield return new WaitForSeconds(2);
        if (healthIcon && (life > maxLife || life < 0))
            healthIcon.renderer.enabled = false;
        if (life < 0)
            Destroy(transform.gameObject);
    }
}
